<?php

namespace App\Http\Controllers;

use App\Libs\Commons\MyMessage;
use App\Services\Garage\AccountService;
use Laravel\Lumen\Routing\Controller as LumenController;

class ApiBaseController extends LumenController
{

    //            定义全局信息
//    public $user_id;
//    public $fix_id;
//    public $realname;

    public function __construct()
    {
        //校验是否登陆
        $this->logined();
    }

    /**
     * 根据token获取登陆信息
     */
    public function logined()
    {
        $route = request()->route()[2];
        $path = strtolower($route['apiv'] . '/' . $route['module'] . '/' . $route['ctl'] . '/' . $route['action']);
        if (!in_array($path, config('white'))) {
            $account = AccountService::getLoginInfo();
            if (empty($account)) {
                $this->die(MyMessage::NOLOGIN);
            }

//            定义全局信息
//            $this->user_id = $account['id'];
//            $this->fix_id = $account['fix_id'];
//            $this->realname = $account['realname'];
        }
    }

    /**
     * 未登录拦截
     * @param string $code
     * @param string $msg
     */
    public function die($code = '', $msg = '')
    {
        header('Content-Type:application/json');
        die(json_encode([
            'code' => $code ? $code : MyMessage::ERROR,
            'msg' => $msg ? $msg : MyMessage::getMessage($code),
            'data' => [],
        ], JSON_UNESCAPED_UNICODE));
    }

    /**
     * 返回消息
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data = [])
    {

        return response()->json([
            'code' =>  MyMessage::SUCCESS,
            'msg' => MyMessage::getMessage(MyMessage::SUCCESS),
            'data' => $data ?? [],
        ]);
    }

    /**
     * 异常信息
     * @param string $code
     * @param string $msg
     * @return \Illuminate\Http\JsonResponse
     */
    public function fail($code = '', $msg = '')
    {
        return response()->json([
            'code' => $code ? $code : MyMessage::ERROR,
            'msg' => $msg ? $msg : MyMessage::getMessage($code),
            'data' => [],
        ]);
    }
}
